package net.isger.brick.raw.depot;

import java.io.IOException;
import java.io.InputStreamReader;

import net.isger.brick.raw.Artifact;
import net.isger.brick.raw.Seed;
import net.isger.brick.util.Files;

import com.google.gson.GsonBuilder;

public class GsonArtifact implements Artifact {

    private GsonBuilder builder;

    private Seed seed;

    public GsonArtifact(Seed seed) {
        this.seed = seed;
        this.builder = new GsonBuilder();
        this.builder.registerTypeAdapterFactory(GsonAdapter.FACTORY);
    }

    public Seed getSeed() {
        return seed;
    }

    public Object use(String id, Object... args) {
        Object result = null;
        if (id.equalsIgnoreCase("transform")) {
            InputStreamReader reader = null;
            try {
                reader = new InputStreamReader(seed.getInputStream());
                result = this.builder.create().fromJson(
                        reader,
                        (args != null && args.length > 0 ? (Class<?>) args[0]
                                : Object.class));
            } catch (IOException e) {
            } finally {
                Files.close(reader);
            }
        }
        return result;
    }
}
